package talk.Net;

import talk.Data.Constant;
import talk.Data.DES;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Created by debby on 2018/3/27.
 * 描述:Retrofit配置
 */

public class RetrofitUtil {


    private static Retrofit retrofit;
    private static final String APPKEY = "RC-App-Key";
    private static final String NONCE = "RC-Nonce";
    private static final String TIMESTAMP = "RC-Timestamp";
    private static final String SIGNATURE = "RC-Signature";

    static {
        OkHttpClient client = new OkHttpClient
                .Builder()
                .readTimeout(15, TimeUnit.MINUTES)
                .connectTimeout(Apis.TIME_OUT, TimeUnit.SECONDS)
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request.Builder builder = chain.request().newBuilder();

                        String nonce = String.valueOf(Math.random() * 1000000);
                        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
                        String signature = DES.sha1(Constant.App_Secret + nonce + timestamp);//数据签名。

                        builder.addHeader(APPKEY, Constant.App_Key);
                        builder.addHeader(NONCE, nonce);
                        builder.addHeader(TIMESTAMP, timestamp);
                        builder.addHeader(SIGNATURE, signature);

                        Request request = builder.build();
                        return chain.proceed(request);
                    }
                })
                .build();
        retrofit = new Retrofit.Builder()
                .baseUrl(Apis.Talk_URL)
                .client(client)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();

    }

    public static ApisService getApisService() {
        ApisService apisService = retrofit.create(ApisService.class);
        return apisService;
    }


}
